<?php
/*--------------------------------------------
Переведення дати в юникс-формат
---------------------------------------------*/	
	function unix_date($d){
		return strtotime($d);
	}


/*--------------------------------------------
Редагування профилю
---------------------------------------------*/
	function editor_profile(){//форма редагування профілю
		$query="SELECT username, id, email, mobile, login, personal_file FROM user WHERE id = '{$_SESSION['id']}';";
		$res=mysql_query($query);
		$row=mysql_fetch_array($res);
		$up_username = $row['username'];
		$up_email = $row['email'];
		$up_id = $row['id'];
		$up_mobile = $row['mobile'];
		$up_personal_file = $row['personal_file'];
		
		$GLOBALS['h1'] = "Редактирование своего профиля {$row['login']}";
		$GLOBALS['content'] = <<<HTML
		<div class="row-fluid">
			<div class="span6">
				<form class="well form-inline" method="POST" ENCTYPE="multipart/form-data" action="/?action=edit_profile_do">
					<div class="row-fluid">
						<label>E-mail</label>
						<input type="text" name="email" class="span12" value="{$up_email}"/>
					</div>
					<div class="row-fluid">
						<label>Аватар</label>
						<input type="file" name="userfile"/>
					</div>
					<div class="row-fluid">
						<label>ФИО</label>
						<input type="text" name="username" class="span12" value="{$up_username}"/>
					</div>
					<div class="row-fluid">
						<label>Телефон</label>
						<input type="text" name="mobile" class="span12" value="{$up_mobile}"/>
					</div>
					<div class="row-fluid">
						<button type="submit" class="btn">Сохранить изменения</button>
					</div>
				</form>
			</div>
		</div>
HTML;
	}
	
	function edit_profile_do(){//редагування юзера
		if($_FILES['userfile']['name'] != '' && $_FILES['userfile']['size'] < 1024*3*1024){
			$uploadfile = 'users_files/'.md5(time()).'.jpg';
			if(move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)){
				//витянути з бази і видалити стару аву
				$query="SELECT ava FROM user WHERE id = '{$_SESSION['id']}';";
				$res=mysql_query($query);
				$row=mysql_fetch_array($res);
				$old_ava = '.'.$row['ava'];
				unlink($old_ava);
			}
			$strSQL = 'UPDATE user SET ava = "/'.$uploadfile.'", username = "'.$_POST["username"].'", email = "'.$_POST["email"].'", mobile = "'.$_POST['mobile'].'", personal_file = "'.$_POST['personal_file'].'" WHERE id = "'.$_SESSION['id'].'"';
		}else{
			$strSQL = 'UPDATE user SET  username = "'.$_POST["username"].'", email = "'.$_POST["email"].'", mobile = "'.$_POST['mobile'].'", personal_file = "'.$_POST['personal_file'].'" WHERE id = "'.$_SESSION['id'].'"';
		}
		mysql_query($strSQL);
		header('Location: /?action=user_profile', true, 303);
	}

/*--------------------------------------------
Все сотрудники 
---------------------------------------------*/

	function select($text,$zm){
		$sel=' selected="selected" ';
		if (strstr($text, $zm)){
			$pos = strpos($text, $zm);
			$start = substr($text, 0, $pos);
			$end = substr($text, $pos, 1000000000);
			$text = $start.$sel.$end;
			return $text;
		}
	}

	
	function allusers(){
		
		$query="SELECT * FROM user";
		$res=mysql_query($query);
		
		$query1="SELECT MAX(service_center) FROM user";
		$res1 = mysql_query($query1);
		$max= mysql_fetch_array($res1);
		$li = '';
		for($i=1; $i<=$max[0]; $i++){
			$li.='<li class="btn btn-info btn-mini" rel="sc'.$i.'">СЦ '.$i.'</li>';
		}
		$GLOBALS['content'] .= <<<TPL
 <script type="text/javascript">
$(document).ready(function(){
 $('#sort_grp li').click(function(){
  if($(this).attr("rel") == "all"){
   $('#sort_cont li').show(400);
  }else{
   $('#sort_cont li.' + $(this).attr("rel")).show(400);
   $('#sort_cont li').not('.' + $(this).attr("rel")).hide(400);
  }
 });
 $('#sort_sc li').click(function(){
  if($(this).attr("rel") == "all"){
   $('#sort_cont li').show(400);
  }else{
   $('#sort_cont li.' + $(this).attr("rel")).show(400);
   $('#sort_cont li').not('.' + $(this).attr("rel")).hide(400);
  }
 });
});
</script>
<ul id="sort_grp" class="btn-group" style="margin-left:0; float:left;">
 <li class="btn btn-info btn-mini" rel="all">Все</li>
 <li class="btn btn-info btn-mini" rel="grp_1">Администраторы</li>
 <li class="btn btn-info btn-mini" rel="grp_3">Мастера</li>
 <li class="btn btn-info btn-mini" rel="grp_2">Менеджеры</li>
 <li class="btn btn-info btn-mini" rel="grp_4">Старшие&nbsp;менеджера</li>
 <li class="btn btn-info btn-mini" rel="grp_5">Кладовщики</li>
</ul>
<ul id="sort_sc" class="btn-group" style="margin-right:0; float:right;">
 <li class="btn btn-info btn-mini" rel="all">Все</li>
 {$li}
 </ul>
<div class="row-fluid" id="sort_cont">
 <div class="span12 tac">
  <ul class="ov_boxes">
TPL;
		
		while($row = mysql_fetch_array($res)){
			$link = get_user_link($row['id']);
			$avatar = $row['ava'];
			$rank = $row['rank'];
			$name = $row['username'];
			$GLOBALS['content'] .= <<<TPL
			<li class="sc{$row['service_center']} grp_{$row['perm']}" style="display: inline-block;">
      <div class="p_bar_up p_canvas">
        <img style="max-width:60px; max-height:70px;" src="{$avatar}" alt="">
      </div>
      <div class="ov_text">
        {$link}
          <strong>{$name}</strong>
        </a>{$rank}
      </div>
    </li>
	
TPL;
		}
		
			$GLOBALS['content'] .= <<<TPL
	</ul></div></div>
TPL;
	
	$GLOBALS['h1'] = 'Все сотрудники';
	}

/*--------------------------------------------
Профили
---------------------------------------------*/
	function user_profile() {
		if(isset($_GET['id'])){
			$id = intval($_GET['id']);
		}else{
			$id = $_SESSION['id']; 
		}
		$query="SELECT perm, username, rank, email, points, login, mobile, ava, service_center, fine FROM user WHERE id='{$id}'";
		$res=mysql_query($query);
		$row=mysql_fetch_array($res);
		
		$but='';
		$but1='';
		$fine='';
		
		
		if($id == $_SESSION['id']){
			$but = '<div class="row-fluid"><a href="/?action=editor_profile" class="btn btn-danger right">Редактировать профиль</a></div>';
			if($row['perm']==3){
			$but1 = '<div class="row-fluid"><a href="/?action=ball" class="btn btn-danger right">Статистика</a></div>';
			}
		}
		
		
		$group = '';
		if($row['perm'] == 1){$group = 'Администратор';}
		elseif($row['perm'] == 2){$group = 'Менеджер';}
		elseif($row['perm'] == 3){$group = 'Мастер';}
		elseif($row['perm'] == 4){$group = 'Старший менеджер';}
		elseif($row['perm'] == 5){$group = 'Кладовщик';}
		
		$GLOBALS['h1'] = 'Профиль пользователя &laquo;'.$row['login'].'&raquo;';
		
		$GLOBALS['content'] .= <<<TPL
		{$but}
		{$but1}
		{$fine}
		<form class="form-horizontal">
			<fieldset>
				<div class="control-group formSep">
					<img src="{$row['ava']}" alt="" style="max-width:300px; max-height:300px;" />
				</div>
				<div class="control-group formSep">
					<label class="control-label">ФИО:</label>
					<div class="controls text_line">{$row['username']}</div>
				</div>
				<div class="control-group formSep">
					<label class="control-label">Группа:</label>
					<div class="controls text_line">{$group}</div>
				</div>
				<div class="control-group formSep">
					<label class="control-label">Должность:</label>
					<div class="controls text_line">{$row['rank']}</div>
				</div>
				<div class="control-group formSep">
					<label class="control-label">Сервисный центр:</label>
					<div class="controls text_line">{$row['service_center']}</div>
				</div>
				<div class="control-group formSep">
					<label class="control-label">Почта:</label>
					<div class="controls text_line"><a href="mailto:{$row['email']}">{$row['email']}</a></div>
				</div>
				<div class="control-group formSep">
					<label class="control-label">Телефон:</label>
					<div class="controls text_line">{$row['mobile']}</div>
				</div>
				
			</fieldset>
		</form>
TPL;

if($_SESSION['perm']==4 && $row['perm']==3){
			$GLOBALS['content'] .= <<<HTML
			<div class="row-fluid">
				<div class="span6">
					<form class="well form-inline" method="POST" action="/?action=fine_master&id={$_GET['id']}"">
						<div class="row-fluid">
							<label>Штраф</label>
							<input type="text" name="fine" class="span12" value="{$row['fine']}"/>
						</div>
						<div class="row-fluid">
								<button type="submit" class="btn">Оштрафовать</button>
							</div>
					</form>
				</div>
			</div>
HTML;
}
}

/*--------------------------------------------
РЕЙТИНГ ЛУЧШИХ
---------------------------------------------*/
	function order($array, $by) {
		$result = array();
		foreach ($array as $val) {
			if (!is_array($val) || !key_exists($by, $val)) {
				continue;
			}
			end($result);
			$current = current($result);
			while ($current[$by] > $val[$by]) {
				$result[key($result)+1] = $current;
				prev($result);
				$current = current($result);
			}
			$result[key($result)+1] = $val;
		}
		return array_reverse($result);
	}

	function best(){
		$GLOBALS['h1'] = 'Лучшие сотрудники';
		$GLOBALS['content'] .= '<script src="/js/jquery.flot.min.js"></script>';

	for ($j=2;$j<=3;$j++){		
	if ($j==2){$h4 = "Менеджеры";}
	elseif ($j==3){$h4 = "Мастера";}

		$GLOBALS['content'] .= <<<TPL
			<h4 class="heading">{$h4}</h4>
		    <div id="placeholder{$j}" style="width:600px;height:300px;"></div>
			<script type="text/javascript">
			$(function(){
TPL;
	
		$times[] = date("Y/m/d",time()-2678400);
		$times[] = date("Y/m/d",time()-2678400*2);
		$times[] = date("Y/m/d",time()-2678400*3);
		$times[] = date("Y/m/d",time()-2678400*4);		
	

		$query="SELECT id,perm FROM user WHERE perm='{$j}'";
		$res2=mysql_query($query);
		
		while ($row2=mysql_fetch_array($res2)){
			
			$id = $row2['id'];
			$perm = $row2['perm'];
			
			switch($perm)
			{
			case 3:		
		
				for ($i=1;$i<=4;$i++){
			
					$time=time()-2678400*$i; $timeend = $time+2678400;
					$time_correction = " AND date_admision_remont>{$time} AND date_admision_remont<{$timeend} ";
					
					$query="SELECT count(*) as co FROM orders WHERE refusal='' {$time_correction}";
					$res=mysql_query($query);
					$row=mysql_fetch_array($res);
					$all_orders = $row['co'];	
					if($all_orders==0){$all_orders=1;}

					$query="SELECT count(*) as hims FROM orders WHERE id_master={$id} AND refusal='' {$time_correction}";
					$res=mysql_query($query);
					$row=mysql_fetch_array($res);
					$all_hims = $row['hims'];		
					if($all_hims==0){$all_hims=1;}
					
					//Производительность главная
					$query="SELECT count(*) as him FROM orders WHERE bool_ready=1 AND id_master={$id} AND refusal='' {$time_correction}";
					$res=mysql_query($query);
					$row=mysql_fetch_array($res);
					$done_by_him = $row['him']*0.5;
					$perf1 = round(100*$row['him']/$all_orders , 2);

					//Производительность второстепенная
					$query="SELECT count(*) as him FROM orders WHERE bool_ready=0 AND id_master={$id} AND refusal='' {$time_correction}";
					$res=mysql_query($query);
					$row=mysql_fetch_array($res);
					$perf2 = round(100*$row['him']/$all_orders , 2);//какая-то непонятная вещь

					//Профессионализм
					$query="SELECT count(*) as him FROM orders WHERE bool_ready=2 AND id_master={$id} AND refusal='' {$time_correction}";
					$res=mysql_query($query);
					$row=mysql_fetch_array($res);
					$prof = round(100*$row['him']/$all_hims , 2);
					
					//Общая оценка работы
					if ($i==1) {$total[$id]['last'] = round($perf1+$perf2/2+$prof/4, 2);}
					if ($i==2) {$total[$id]['prev'] = round($perf1+$perf2/2+$prof/4, 2);}
					if ($i==3) {$total[$id]['prevprev'] = round($perf1+$perf2/2+$prof/4, 2);}	
					if ($i==4) {$total[$id]['prev3'] = round($perf1+$perf2/2+$prof/4, 2);}	
					$total[$id]['id'] = $id;					
				
				}
				break;
			
			case 2: 
			
				for ($i=1;$i<=4;$i++){
			
					$time=time()-2678400*$i; $timeend = $time+2678400;
					$time_correction = " AND date_admision>{$time} AND date_admision<{$timeend} ";
					
					$query="SELECT count(*) as co FROM orders WHERE refusal=''  {$time_correction}";
					$res=mysql_query($query);
					$row=mysql_fetch_array($res);
					$all_orders = $row['co'];
					if($all_orders==0){$all_orders=1;}
					
					$query="SELECT count(*) as hims FROM orders WHERE id_menedger={$id}  {$time_correction}";
					$res=mysql_query($query);
					$row=mysql_fetch_array($res);
					$all_hims = $row['hims'];		
					if($all_hims==0){$all_hims=1;}
					
					//Согласие на полную сумму
					$query="SELECT count(*) as him FROM orders WHERE id_menedger={$id} AND adopted_value='1'  {$time_correction}";
					$res=mysql_query($query);
					$row=mysql_fetch_array($res);
					$perf1 = round(100*$row['him']/$all_hims , 2);

					//Согласие на ниже сумму
					$query="SELECT count(*) as him FROM orders WHERE id_menedger={$id} AND adopted_value='2'  {$time_correction}";
					$res=mysql_query($query);
					$row=mysql_fetch_array($res);
					$perf2 = round(100*$row['him']/$all_hims , 2);

					//Отказ от всех сумм
					$query="SELECT count(*) as him FROM orders WHERE id_menedger={$id} AND refusal != ''  {$time_correction}";
					$res=mysql_query($query);
					$row=mysql_fetch_array($res);
					$refusals = round(100*$row['him']/$all_hims , 2);
					
					//Общее
					$query="SELECT count(*) as him FROM orders WHERE id_menedger={$id} {$time_correction}";
					$res=mysql_query($query);
					$row=mysql_fetch_array($res);
					if ($i==1) {$total[$id]['last'] = $perf1+$perf2;}
					if ($i==2) {$total[$id]['prev'] = $perf1+$perf2;}
					if ($i==3) {$total[$id]['prevprev'] = $perf1+$perf2;}
					if ($i==4) {$total[$id]['prev3'] = $perf1+$perf2;}					
					$total[$id]['id'] = $id;
				}			
				
				break;
			}
			
	}				
			$total = order($total, 'last');
			$i=0;
			$st = 'var all_data = [';
			foreach($total as $key => $value){
			$i++;
			$query="SELECT * FROM user WHERE id = '{$total[$key]['id']}';";
			$res1=mysql_query($query);
			$row=mysql_fetch_array($res1);

			$st .= <<<TPL
				{ label: "{$row['login']}", data: [
					["{$times[3]}", {$total[$key]['prev3']}],				
					["{$times[2]}", {$total[$key]['prevprev']}],
					["{$times[1]}", {$total[$key]['prev']}],
					["{$times[0]}", {$total[$key]['last']}]
				]
				
TPL;
			if ($i==3) break;
			$st .= '},';
			}

			$st .= '];';
			
			$GLOBALS['content'] .= $st;
			
			$GLOBALS['content'] .= <<<TPL
			// преобразуем даты в UTC
			for(var j = 0; j < all_data.length; ++j) {
			   for(var i = 0; i < all_data[j].data.length; ++i)
				 all_data[j].data[i][0] = Date.parse(all_data[j].data[i][0]);
			}			
			
			
			var plot_conf = {
			series:{
			lines:{
				show: true,
				lineWidth: 2
			},
			     bars: {

      horizontal: false
    }
 },
 xaxis: {
   mode: "time",
   timeformat: "%0m/%y",
 }
};
				$.plot($("#placeholder{$j}"), all_data, plot_conf);
			});
			</script>
TPL;
	unset ($total);
	}
}

/*--------------------------------------------
ВНУТРІШНІ ФУНКЦІЇ
---------------------------------------------*/
	function is_checked($val){//вивід значення галочки
		if((bool)$val == true){
			return 'checked="checked"';
		}else{
			return '';
		}
	}
	
	
	function get_user_link($user_id){//вивід посилання на профіль колистувача
		$query="SELECT * FROM user WHERE id = '{$user_id}';";
		$res=mysql_query($query);
		$row=mysql_fetch_array($res);
		return '<a href="/?action=user_profile&id='.$row['id'].'">'.$row['login'].'</a>';
	}	
/*--------------------------------------------
СТАТУС ЗАКАЗА
---------------------------------------------*/
	function get_status($zk){//статус заказа
		$status = '';
		$status2 = '';
		$status3 = '';
		$status4 = '';
		
		if ($_SESSION['perm']==1 || $_SESSION['perm']==2 || $_SESSION['perm']==4){ 
		if($zk['bool_ready'] == 1){$status = '<span class="alert alert-success stt">Сделан</span>';}
		elseif($zk['bool_ready'] == 2){$status = '<span class="alert alert-error stt">Не&nbsp;сделан</span>';}
		elseif($zk['bool_ready'] == 0 && $zk['id_master'] != 0){$status = '<span class="alert alert-info stt">В&nbsp;ремонтe</span>';}
		elseif($zk['bool_work'] != 0 && $zk['id_master'] == 0){$status = '<span class="alert alert-info stt" style="font-size:80%;">В&nbsp;очереди&nbsp;на&nbsp;ремонт</span>';}
		elseif($zk['refusal'] != ''){$status = '<span class="alert alert-error stt">Отказ</span>';}
		elseif($zk['date_admision'] != 0 && $zk['bool_diagnosis'] == 0){$status = '<span class="alert stt">На&nbsp;диагностике</span>';}
		elseif($zk['date_giving'] != 0){$status = '<span class="alert alert-success stt">Выдан</span>';}
		elseif($zk['bool_work'] == 0 && $zk['bool_ready'] == 0 && $zk['refusal']=='' && $zk['date_giving']==0 && $zk['bool_pozvon'] == 1){$status = '<span class="alert stt">Отправить&nbsp;в&nbsp;ремонт</span>';}
		elseif($zk['bool_diagnosis'] == 1){$status = '<span class="alert stt">Нужно&nbsp;позвонить</span>';}
		else{$status = '-';}
		
		if($zk['bool_diagnosis'] == 1) {$status2 = '<br><img src="/img/dign_a.png" alt="" title="Диагностика сделана"/>';}
		elseif($zk['bool_diagnosis'] == 0) {$status2 = '<br><img src="/img/dign.png" alt="" title="На диагностике"/>';}
		
		if($zk['bool_pozvon'] == 1) {$status3 = '<br><img src="/img/podzv_a.png" alt="" title="Позвонили"/>';}
		elseif($zk['bool_pozvon'] == 0) {$status3 = '<br><img src="/img/podzv.png" alt="" title="Пока не позвонили"/>';}
		
		if($zk['warranty'] == 1) {$status4 = '<br><span class="alert alert-error stt">По&nbsp;гарантии</span></br>';}
		}
		else {
			if($zk['job_bool']==1 && $zk['job']!=''){$status='<span class="alert alert-info stt">Заказана</span>';}
			elseif($zk['job_bool']==2 && $zk['job']!=''){$status='<span class="alert alert-error stt">Не&nbsp;придет</span>';}
			elseif($zk['job_bool']==3 && $zk['job']!=''){$status='<span class="alert alert-success stt">Пришла</span>';}
		}
		return $status.$status2.$status3.$status4;
	}
	
	
	function get_status_hist($zk){//статус заказа
		$status = '';
		$status2 = '';
		
		if($zk['bool_ready'] == 1){$status = '<span class="alert alert-success stt">Сделан</span></br></br>';}
		elseif($zk['bool_ready'] == 2){$status = '<span class="alert alert-error stt">Не&nbsp;сделан</span></br></br>';}
		
		if($zk['job_bool']==1 && $zk['job']!=''){$status2='<span class="alert alert-info stt">Заказана</span>';}
		elseif($zk['job_bool']==2 && $zk['job']!=''){$status2='<span class="alert alert-error stt">Не&nbsp;придет</span>';}
		elseif($zk['job_bool']==3 && $zk['job']!=''){$status2='<span class="alert alert-success stt">Пришла</span>';}
		//else{$status = '-';}
		
		
		return $status.$status2;
	}



/*--------------------------------------------
ЧАТ
---------------------------------------------*/
	function chat(){
	$GLOBALS['chat'] = <<<END
	<div id="uchat" class="green">
		<div id="chat_min" title="свернуть/развернуть чат"></div>
		<div id="respond">
			<div id="chatUsers"></div>
			<ul id="chatLineHolder"></ul>
			<div id="chatBottomBar">
				<form id="submitForm" method="post" action="">
					<textarea id="chatText" name="chatText" ></textarea>
					<input type="submit" class="right" value="Отправить" />
				</form>
			</div>
			<script type="text/javascript">
				var uzerlogin = '{$_SESSION['login']}';
			</script>
			<script type="text/javascript" src="/chat/chat.js"></script>
		</div>
	</div>
END;

	}
	
/*--------------------------------------------
ФАЙЛОВИЙ МЕНЕДЖЕР
---------------------------------------------*/
	function filemanager(){
		$GLOBALS['h1'] = 'База данных';
		$GLOBALS['content'] = '<iframe width="100%" height="500" frameborder="0" src="/file_manager/browse.php"></iframe>';
	}

/*--------------------------------------------
ЖАЛОБИ І ПРОПОЗИЦІЇ
---------------------------------------------*/
	function add_complaint_do(){//додати жалобу
		$date_complaint = time();
		$complaint = trim(htmlspecialchars($_POST['complaint']));

		$query = 'INSERT INTO book_com (username, date_start, visibility, complaint) VALUES ("'.$_SESSION['id'].'", "'.$date_complaint.'", "'.(bool)$_POST['visibility'].'", "'.$complaint.'")';
		$result = mysql_query($query);

		header('Location: /?action=list_complaint_all', true, 303);
	}

	function list_complaint_all(){//список жалоб
		$query="SELECT * FROM book_com WHERE visibility = true";
		$res=mysql_query($query);
		
		$GLOBALS['h1'] = 'Жалобы и пожелания';
		while($row=mysql_fetch_array($res)){
			$userlink = get_user_link($row['username']);
			$date = date('Y.m.d H:i', $row['date_start']);
			
			$GLOBALS['content'] .= <<<TPL
			<blockquote>
				<p>{$row['complaint']}</p>
				<small>{$userlink}, {$date}</small>
			</blockquote>
TPL;
		}
		
		$GLOBALS['content'] .= <<<TPL
		<div class="row-fluid">
			<div class="span6">
				<form method="POST" action="/?action=add_complaint_do" class="well form-inline">
					<p class="f_legend">Написать жалобу или пожелание</p>
					<div class="row-fluid">
						<div class="span12">
							<textarea rows="3" class="span12" name="complaint"></textarea>
						</div>
					</div>
					<div class="row-fluid">
						<div class="span12">
							<label class="checkbox">
								<input type="checkbox" name="visibility" checked="checked"/>
								Показывать всем
							</label>
						</div>
					</div>
					<div class="row-fluid">
						<div class="span12">
							<button type="submit" class="btn">Отправить</button>
						</div>
					</div>
				</form>
			</div>
		</div>
TPL;
	}
	
	
	
/*--------------------------------------------
НОВИНИ
---------------------------------------------*/
	function list_news_all(){//список новин
		$query="SELECT id, name_news, date_news, short_news, long_news FROM news";
		$res=mysql_query($query);
		
		$GLOBALS['h1'] = 'Новости';
		while($row=mysql_fetch_array($res)){
			$date = date('Y.m.d H:i', $row['date_news']);
			$GLOBALS['content'] .= <<<TPL
			<h3><a href="/?action=long_story&id={$row['id']}">{$row['name_news']}</a></h3>
			<span class="pull-right label label-info ttip_t">{$date}</span>
			<div class="row-fluid">{$row['short_news']}</div>
			<hr/>
TPL;
		}
	}
	
	function long_story(){//повна новина
		$query="SELECT id, name_news, date_news, short_news, long_news FROM news  WHERE id = '".$_GET['id']."'";
		$res=mysql_query($query);
		$row=mysql_fetch_array($res);
		$date = date('Y.m.d H:i', $row['date_news']);
		
		$GLOBALS['h1'] = $row['name_news'];
		$GLOBALS['content'] = "<div class='post-meta'>Добавлено в {$date}</div>{$row['long_news']}";		
	}
	
	
/*--------------------------------------------
ВИХІД І АВТОРИЗАЦІЯ
---------------------------------------------*/
	function login(){//форма авторизації
		$GLOBALS['content'] = <<<TPL
		<form action="?action=login_do" method="post" id="login_form">
			<div class="top_b">Вход</div>
			<div class="cnt_b">
				<div class="formRow">
					<div class="input-prepend">
						<span class="add-on"><i class="icon-user"></i></span><input type="text" name="login" placeholder="Логін" value=""/>
					</div>
				</div>
				<div class="formRow">
					<div class="input-prepend">
						<span class="add-on"><i class="icon-lock"></i></span><input type="password" name="password" placeholder="Пароль" value=""/>
					</div>
				</div>
			</div>
			<div class="btm_b clearfix">
				<button class="btn btn-inverse pull-right" type="submit">Війти</button>
			</div>
		</form>
TPL;
	}

	function login_do(){//авторизація
		if(isset($_POST['login'])){
			$login = $_POST['login']; 
			if($login == ''){
				unset($login);
				exit ("Введіть логін");
			}		 
		}

		if(isset($_POST['password'])){
			$password = $_POST['password']; 
			if ($password == '') {
				unset($password);
				exit ("Введіть пароль");
			}
		}

		$password = md5($password.$login);
		$user = mysql_query("SELECT id, perm, service_center FROM user WHERE login='$login' AND password='$password'");
		$id_user = mysql_fetch_array($user);
		
		if(empty($id_user['id'])){
			exit ("Вибачте, але введений вами логін чи пароль невірний.");
		}

		else{
			$_SESSION['perm'] = $id_user['perm']; 
			$_SESSION['login'] = $login; 
			$_SESSION['id'] = $id_user['id']; 
			$_SESSION['sc'] = $id_user['service_center']; 
		}

		header('Location: /', true, 303);
	}

	function logout(){//вихід
		unset($_SESSION['perm']);
		unset($_SESSION['login']); 
		unset($_SESSION['id']);
		unset($_SESSION['sc']);
		header('Location: /', true, 303);
	}
	

	
/*--------------------------------------------
СТАТИЧНІ СТОРІНКИ
---------------------------------------------*/
	function list_page_all(){
		$query="SELECT id, name_page, cont_page FROM static_page WHERE id = '".$_GET['id']."'";
		$res=mysql_query($query);
		$row=mysql_fetch_array($res);

		$GLOBALS['h1'] = $row['name_page'];
		$GLOBALS['content'] = $row['cont_page'];
	}
?>